
package tests;

import org.apache.log4j.*;
import org.hibernate.*;
import org.hibernate.cfg.*;

public class HibernateUtil
{
	public static final Logger logger = Logger.getLogger(HibernateUtil.class);
	public static SessionFactory sessionFactory = null;
	public static Configuration conf = null;

	private synchronized static void prepareConfiguration()
	{
		try
		{
			if (conf == null)
			{
				conf = new Configuration()
				//.addPackage("cz.czu.pef.DataModelling") //the fully qualified package name
				//.addAnnotatedClass(Address.class)
				//.addAnnotatedClass(Person.class)
				//.addResource("test/animals/orm.xml")
				.configure();
			}
		}
		catch (Throwable ex)
		{
			// Log exception!
			throw new ExceptionInInitializerError(ex);
		}
	}

	private synchronized static void prepareSessionFactory()
	{
		try
		{
			prepareConfiguration();
			if (sessionFactory == null)
			{
				sessionFactory = conf.buildSessionFactory();
			}
		}
		catch (Throwable th)
		{
			logger.log(Level.FATAL, "prepareSessionFactory():: Caught throwable: " + th.getMessage(), th);
			throw new ExceptionInInitializerError(th);
		}
	}

	public static Session getSession() throws HibernateException
	{
		prepareSessionFactory();
		return sessionFactory.openSession();
	}

	public static void closeSession(Session session)
	{
		try
		{
			// Actual contact insertion will happen at this step
			if (session != null)
			{
				session.flush();
				session.close();
			}
		}
		catch (Exception e)
		{
			System.out.println(e.getMessage());
		}
	}
	/*
	private static EntityManagerFactory emf;
	private static EntityManager em;
	public static void getSessionByEntityManagerFactory()
	{
		// THIS IS NOT WORKING - EJB3/JPA requires Container (Application server) or JTA must be (somehow) explicitly initialized!
		// Please see this as an example:
		//    http://community.jboss.org/wiki/ImplementingstandaloneJPAJTAHibernateapplicationoutsideJ2EEserverusingInfinispan2ndlevelcache
		BasicConfigurator.configure();
		Logger.getLogger("org").setLevel(Level.ERROR);

		emf = Persistence.createEntityManagerFactory("dataModellingPersistenceUnit-LOCAL");
		em = emf.createEntityManager();
		performTest((Session)em.getDelegate());
		System.out.println("YEAH");

		em.close();
	}

	public static Session getSession_ByHibernateConfiguration()
	{
		Session session = null;

		try
		{
			// This step will read hibernate.cfg.xml
			// and prepare hibernate for use
			SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
			session = sessionFactory.openSession();
			performTest(session);
			
		}
		catch (Exception e)
		{
			System.out.println(e.getMessage());
		}
		finally
		{
			// Actual contact insertion will happen at this step
			session.flush();
			session.close();
		}
	}
	*/

}
